/*
 * Copyright 2008 Max Kugland
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.splink.library.reflection {
	/**
	 * <code>Method</code> represents a method of a class. 
	 * 
	 * @author Max Kugland
	 */
	public class Method implements IMember {
		private var _clazz : Class;
		private var _name : String;
		private var _returntype : String;
		private var _params : Array;
		private var _isStatic : Boolean;
		private var _metaData : Array;

		/**
		 * @param clazz the class to which the <code>Method</code> belongs
		 * @param name the name of the <code>Method</code>
		 * @param returntype the return type of the <code>Method</code>
		 * @param params an array of <code>Parameter</code> objects which are expected by the method
		 * @param isStatic true if the <code>Method</code> is static, otherwise false
		 * @param metaData optional metadata (annotations)
		 */
		public function Method(clazz : Class, name : String, returnType : String, params : Array, isStatic : Boolean, metadata : Array = null) {
			_clazz = clazz;
			_name = name;
			_returntype = returnType;
			_params = params;
			_isStatic = isStatic;
			_metaData = metadata;
		}

		/**
		 * @inheritDoc
		 */
		public function get clazz() : Class {
			return _clazz;
		}

		/**
		 * @inheritDoc
		 */
		public function get name() : String {
			return _name;
		}

		/**
		 * @inheritDoc
		 */
		public function get returntype() : String {
			return _returntype;
		}

		/**
		 * @return an array of Parameter objects
		 */
		public function get params() : Array {
			return _params;
		}

		/**
		 * @return whether the <code>Method</code> has parameters or not
		 */
		public function get hasParams() : Boolean {
			return _params.length > 0;
		}

		/**
		 * @inheritDoc
		 */
		public function get isStatic() : Boolean {
			return _isStatic;
		}

		/**
		 * @inheritDoc
		 */
		public function invoke(instance : Object = null, params : * = null) : * {
			var fnc : Function = null;
			if(_isStatic)
				fnc = _clazz[_name];
			else if(instance)
				fnc = instance[_name];

			if(instance && fnc != null) {
				if(params)
					return fnc.apply(instance, params);
				else
					return fnc.apply(instance);
			}
		}

		/**
		 * @inheritDoc
		 */
		public function get metaData() : Array {
			return _metaData;
		}
	}
}
